package com.woniuxy.rbac.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.woniuxy.rbac.entity.Member;
import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@Slf4j
@Controller
@RequestMapping("member")
public class MemberController {
    @GetMapping("regist")
    public String regist() {
        return "regist";
    }

    @PostMapping("regist")
    public String regist(Member member, HttpSession session) {
        log.debug("账号:{},密码：{}", member.getAccount(), member.getPassword());
        session.setAttribute("member1", member);
        return "redirect:/menmer/login";
    }

    @GetMapping("login")
    public String login(String reback, Model model) {
        model.addAttribute("reback", reback);
        return "login";
    }

    @PostMapping("login")
    public String login(Member member, String reback, Model model, HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(member.getAccount(), member.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //保存Session
            session.setAttribute("member",subject.getPrincipal());
            return "index";
        } catch (UnknownAccountException uae) {
            System.out.println("账号不存在");
        } catch (IncorrectCredentialsException ice) {
            System.out.println("密码不正确");
        }
        return "login";
    }

//    @GetMapping("logout")
//    public String logout(HttpSession session) {
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
////        session.removeAttribute("member");
//        return "redirect:/member/login";
//    }

    @Autowired
    private MemberService memberService;

    /**
     * @param account
     * @return 如果账号存在，返回true；否则，返回false
     */
    @GetMapping("exist")
    @ResponseBody
    public ResponseResult<Boolean> exist(String account) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        long conut = memberService.count(queryWrapper);
        return new ResponseResult<>(conut != 0);
    }

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/captcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("verificationCode", createText);
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
